package daoimpl

import (
	"fmt"
	"log"
	"ustcLab/conf"
	"ustcLab/server/dao/bean"
)

// select
func QueryDashBoard() (int, []*bean.TDashBoard, error) {
	var dashboard []*bean.TDashBoard
	count, err := GetInstance().FindAndCount(&dashboard)
	if err != nil {
		log.Fatalln("[QueryDashBoard] fail to find dashboard info, err: ", err)
		return 0, nil, err
	}
	log.Printf("[QueryDashBoard] query dashboard info success. count = %d\n", count)
	return int(count), dashboard, nil
}

// insert
func InsertDashBoard(dashBoard *bean.TDashBoard) (int, error) {
	count, err := GetInstance().Insert(&dashBoard)
	if err != nil {
		log.Fatalln("[InsertDashBoard] fail to insert to dashboard info, err: ", err)
		return 0, err
	}
	log.Printf("[InsertDashBoard] insert to dashboard info success. count = %d\n", count)
	return int(count), nil
}

// update by random
func ModifyDashBoard(name string, value float64) (int, error) {
	cond := &bean.TDashBoard{
		FName: name,
	}
	res, err := GetInstance().Get(cond)
	if err != nil {
		log.Fatalln("[ModifyDashBoard] err: ", err)
		return 0, err
	}
	if !res {
		log.Fatalf("[ModifyDashBoard] %s\n", conf.ErrorDatabaseNotExists)
		return 0, conf.String2Error[conf.ErrorDatabaseNotExists]
	}
	dataPoints := fmt.Sprintf("{%v:%f}", 0, value)

	affected, err := GetInstance().Update(&bean.TDashBoard{
		FDataPoints: dataPoints,
	}, cond)

	if err != nil {
		log.Fatalln("[ModifyMonitorInfo] err: ", err)
	}
	return int(affected), err
}

func ModifyDashBoardOne(dashBoard *bean.TDashBoard) (int, error) {
	cond := &bean.TDashBoard{
		FName: dashBoard.FName,
	}
	affected, err := GetInstance().Update(dashBoard, cond)

	if err != nil {
		log.Fatalln("[ModifyMonitorInfo] err: ", err)
	}
	return int(affected), err
}
